package com.ibm.spatiotemp.server.config;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

/**
 * 
 * @author xuxiaomin
 * 
 */
public class BackendServerManager {

	public static Logger logger = Logger.getLogger(BackendServerManager.class);
	
	/*for later to support multiple topics*/
	public static ConcurrentHashMap<String, PubSubMetaVector>
	topic2serverMap = new ConcurrentHashMap<String, PubSubMetaVector>();

	static{
		LoadfromFile(LocalConfig.DefaultBackendServerConfigFilePath);
	}
	
	private static void InsertPubSubMeta(String line) {
		PubSubMeta curmeta = new PubSubMeta(line);
		String key = curmeta.getTopic();
		PubSubMetaVector curset = topic2serverMap.get(key);
		if (curset == null) {
			curset = new PubSubMetaVector(PubSubMetaVector.DefaultMaxSize);
			curset.addMetaVector(curmeta);
		} else {
			curset.addMetaVector(curmeta);
		}
		topic2serverMap.put(key, curset);
	}

	public static void LoadfromFile(String filepath) {
		BufferedReader freader = null;
		try {
			freader = new BufferedReader(new FileReader(filepath));
			String curline = null;
			while ((curline = freader.readLine()) != null) {
				InsertPubSubMeta(curline);
			}
		} catch (FileNotFoundException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
	}
	
	/**
	 * random select a meta from a topic's PubSubMetaVector
	 * @param topic
	 */
	public static PubSubMeta getPubSubMetaByTopic(String topic){
		PubSubMetaVector curset = 
				topic2serverMap.get(topic);
		if(curset != null){
			return curset.selectPubSubMeta_Random();
		}
		else
		{
			logger.error("topic not founded : "+ topic);
			return null;
		}
	}
	
}
